import tkinter
import tkinter.ttk
import os

class TreeWindows:
    def __init__(self):
        self.win=tkinter.Tk()
        self.tree=tkinter.ttk.Treeview(self.win)  #树状
        self.ysb=tkinter.ttk.Scrollbar(self.win,orient="vertical",command=self.tree.yview()) #滚动条
        self.xsb=tkinter.ttk.Scrollbar(self.win,orient="horizontal",command=self.tree.xview())
        self.tree.configure(yscroll=self.ysb.set,xscroll=self.xsb.set)
        self.tree.grid(row=0,column=0) 

        self.tree.heading('#0',text='Path',anchor='w') #初始化头部
        self.tree.bind("<<TreeviewSelect>>",self.gosel) #选中绑定
        filepath="E:\黑马19年Java"
        root=self.tree.insert("","end",text=filepath,open=True)
        self.loadtree(root,filepath)

        self.e=tkinter.StringVar()
        self.entry=tkinter.Entry(self.win,textvariable=self.e)
        self.e.set('请选择文件')
        self.entry.grid(row=0,column=2)

        self.ysb.grid(row=0,column=1,sticky="ns")
        self.xsb.grid(row=1,column=0,sticky="ew")
        self.win.grid()

    def loadtree(self,parent,rootpath):
        for path in os.listdir(rootpath): #遍历当前目录
            abspath=os.path.join(rootpath,path) #路径链接
            oid=self.tree.insert(parent,'end',text=path,open=False) #插入数值
            if os.path.isdir(abspath):
                self.loadtree(oid,abspath)

    def gosel(self,event):
        self.select=event.widget.selection() 
        for idx in self.select:
            self.e.set(self.tree.item(idx)["text"])

    def show(self):
        self.win.mainloop()

mytree=TreeWindows()
mytree.show()